package com.itzg.svn;

import java.io.File;
import java.io.FileFilter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;

class Trunk {
	private List<Branch> branches = new LinkedList<Branch>();
	private long totalBranchesCreated = 0;

	private static final FileFilter nonHiddenFileFilter = new FileFilter() {
		@Override
		public boolean accept(File f) {
			return !f.isHidden();
		}
	};
	private List<FileEntry> fileTable;
	private final File baseDir;
	private long fileCount;
	private long totalFileSize;

	public Trunk(File baseDir) {
		this.baseDir = baseDir;
		initFileTable(baseDir);
	}
	
	private void initFileTable(File baseDir) {
		fileTable = new ArrayList<FileEntry>();
		addToFileTable(baseDir, baseDir, fileTable);
		// sort bigger files first, so concurrently modified can be picked off easily from top
		Collections.sort(fileTable, new Comparator<FileEntry>() {
			@Override
			public int compare(FileEntry o1, FileEntry o2) {
				return o1.getFileSize() == o2.getFileSize() ? 0 : (o1.getFileSize() > o2.getFileSize() ? -1 : 1);
			}
		});
	}
	
	private void addToFileTable(File baseDir, File dir, List<FileEntry> fileTable) {
		File[] files = dir.listFiles(nonHiddenFileFilter);
		for (File file : files) {
			if (file.isDirectory()) {
				addToFileTable(baseDir, file, fileTable);
			}
			else {
				fileTable.add(new FileEntry(baseDir, file));
				++fileCount;
				totalFileSize += file.length();
			}
		}
	}

	public long getFileCount() {
		return fileCount;
	}

	public long getTotalFileSize() {
		return totalFileSize;
	}


}
